// ignore_for_file: sort_constructors_first

import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:medical_pro_flutter/api/Api.dart';
import 'package:medical_pro_flutter/components/dialog/FailDialog.dart';
import 'package:medical_pro_flutter/components/dialog/LoadingDialog.dart';
import 'package:medical_pro_flutter/components/dialog/SuccessDialog.dart';
import 'package:medical_pro_flutter/entity/User.dart';

import '../../components/widget/ExpertOrNot.dart';
import '../../utils/StringUtils.dart';
import '../dialog/ExpertListDialog.dart';
import '../dialog/ImageDialog.dart';

class ShowCasePage extends StatefulWidget {
  Map? arguments;
  ShowCasePage(this.arguments);

  @override
  _ShowCasePageState createState() =>
      _ShowCasePageState(arguments: this.arguments);
}

class _ShowCasePageState extends State<ShowCasePage> {
  Map? arguments;
  List? imageList = [];
  List? seg_image_List = [];
  bool _showDeleteButton = false;
  bool _showSegPhotowButton = false;

  TextEditingController nameController = TextEditingController();
  TextEditingController idController = TextEditingController();
  TextEditingController phonenumController = TextEditingController();
  TextEditingController ageController = TextEditingController();
  TextEditingController habitStrController = TextEditingController();
  TextEditingController historyController = TextEditingController();
  TextEditingController resultController = TextEditingController();
  TextEditingController sugController = TextEditingController();
  TextEditingController dateController = TextEditingController();

  _ShowCasePageState({this.arguments});

  @override
  void initState() {
    print('进来了ShowCasePage');
    nameController.text = arguments!['patient_name'];
    idController.text = arguments!['patient_idcard_num'];
    phonenumController.text = arguments!['phone_num'];
    ageController.text = arguments!['patient_age'].toString();
    resultController.text = arguments!['result'];
    print('习惯：${arguments!['habits_str']}');
    habitStrController.text = arguments!['habits_str'];
    dateController.text = arguments!['date'];

    print('上传者：${arguments!['uploder']}');

    if (arguments!['uploder'] == User.job_num) {
      _showDeleteButton = false;
    } else {
      _showDeleteButton = true;
    }

    if (arguments!['expert_sug_list'].isEmpty) {
      sugController.text = '暂无专家建议';
    } else {
      sugController.text = arguments!['expert_sug_list'][0]['expert_sug'];
    }

    if (arguments!['allergy_history'] == 'y') {
      historyController.text = '有';
    } else {
      historyController.text = '无';
    }

    arguments!['image_names'].forEach((v) {
      print(v);

      imageList?.add(
          StringUtils.getCaseImageUrl(arguments!['case_id'].toString(), v));
    });

    print('后：${imageList.toString()}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('详细信息'),
        ),
        body: SingleChildScrollView(
          child: Container(
            alignment: Alignment.center,
            margin: const EdgeInsets.all(20),
            padding: const EdgeInsets.all(5),
            child: Column(
              children: <Widget>[
                Container(
                    margin: const EdgeInsets.all(10),
                    child: TextField(
                      enabled: false,
                      controller: nameController,
                      decoration: InputDecoration(
                          border: OutlineInputBorder(), labelText: '姓名'),
                    )),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    controller: idController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '身份证号'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: phonenumController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '联系电话'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: ageController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '年龄'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: habitStrController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '习惯'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: historyController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '过敏史'),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    enabled: false,
                    keyboardType: TextInputType.number,
                    controller: dateController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '诊断日期'),
                  ),
                ),
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: ImageWrap(),
                ),
                Container(
                  margin: const EdgeInsets.all(10),
                  child: TextField(
                    keyboardType: TextInputType.multiline,
                    // maxLines: whatever,
                    enabled: false,
                    maxLines: null,
                    controller: resultController,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(), labelText: '诊断结果'),
                  ),
                ),
                SingleChildScrollView(
                  scrollDirection: Axis.vertical,
                  child: ImageWrap_Seg(),
                ),
                Offstage(
                    offstage: _showSegPhotowButton,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        // ElevatedButton(
                        //   child: Text('获取分割图'),
                        //   onPressed: _getSegPhotoUrl,
                        //   style: ButtonStyle(
                        //     backgroundColor:
                        //         MaterialStateProperty.all(Colors.blue),
                        //   ),
                        // ),
                      ],
                    )),
                TextField(
                  keyboardType: TextInputType.multiline,
                  // maxLines: whatever,
                  enabled: false,
                  maxLines: null,
                  controller: sugController,
                  decoration: InputDecoration(
                      border: OutlineInputBorder(), labelText: '专家建议'),
                ),
                Offstage(
                    offstage: _showDeleteButton,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          margin: EdgeInsets.only(right: 8.0),
                          child: Text('该条病例是您上传的，您可以删除它'),
                        ),
                        ElevatedButton(
                          child: Text('删除病例'),
                          onPressed: _deleteCase,
                          style: ButtonStyle(
                            backgroundColor:
                                MaterialStateProperty.all(Colors.blue),
                          ),
                        ),
                      ],
                    )),
                ElevatedButton(
                  child: Text('返回'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.all(Colors.blue),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  Widget ImageWrap() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 10,
        spacing: 5,
        children: initFile(),
      ),
    );
  }

  Widget ImageWrap_Seg() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Wrap(
        runSpacing: 10,
        spacing: 5,
        children: initFile_Seg(),
      ),
    );
  }

  initFile() {
    return imageList!
        .map((file) => Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return ImageDialog(file);
                        });
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      child: Image.network(
                        file,
                        width: 100,
                        height: 100,
                        fit: BoxFit.fill,
                      )),
                )
              ],
            ))
        .toList();
  }

  _getSegPhotoUrl() async {
    Response response;
    String url = API.BASE_URL +
        API.GET_SEG_PHOTO_LIST +
        arguments!['case_id'].toString();
    var dio = Dio();
    response = await dio.get(url);
    dio.close();

    if (response.statusCode == 200) {
      print(response.data);
      List<dynamic> res = json.decode(response.data);
      for (int i = 0; i < res.length; i++) {
        res[i] = StringUtils.getSegImageUrl(
            arguments!['case_id'].toString(), res[i]);
      }
      setState(() {
        seg_image_List = res;
        _showSegPhotowButton = true;
      });

      // List va = List<dynamic>.from(response.data);

      // va.forEach((v) {
      //   print(v);

      //   setState(() {
      //     seg_image_List!.add(
      //         StringUtils.getSegImageUrl(arguments!['case_id'].toString(), v));
      //   });
      // });
    }
  }

  initFile_Seg() {
    return seg_image_List!
        .map((file) => Stack(
              children: <Widget>[
                GestureDetector(
                  onTap: () {
                    showDialog(
                        context: context,
                        builder: (context) {
                          return ImageDialog(file);
                        });
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(10)),
                      child: Image.network(
                        file,
                        width: 100,
                        height: 100,
                        fit: BoxFit.fill,
                      )),
                )
              ],
            ))
        .toList();
  }

  _deleteCase() async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text('提示信息'),
            content: Text('若您向专家推送过本病例，该操作会将推送也一并删除，确定删除吗？'),
            actions: <Widget>[
              TextButton(
                  onPressed: () {
                    print('点击了取消');
                    Navigator.pop(context, 'cancel');
                  },
                  child: Text('取消')),
              TextButton(
                  onPressed: () {
                    print('点击了确定');
                    Navigator.pop(context);
                  },
                  child: Text('确定')),
            ],
          );
        });
    if (result == 'cancel') {
      return;
    }
    String url = API.BASE_URL + API.DELETE_CASE;

    print('发出请求：$url');
    Response response;

    try {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return LoadingDialog(text: '请求中...');
          });
      var dio = Dio();
      var formData = FormData.fromMap({
        'illcase_id': arguments!['case_id'],
        'job_num': User.job_num,
      });
      response = await dio.delete(url, data: formData);
      dio.close();

      if (response.statusCode == 200) {
        print(response.data);
        Fluttertoast.showToast(
          msg: '删除成功',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.BOTTOM,
          timeInSecForIosWeb: 3,
          backgroundColor: Colors.white,
          textColor: Colors.black,
          fontSize: 16.0,
        );

        Navigator.pop(context);
        Navigator.pop(context);
      }
    } catch (e) {
      print(e);
      Fluttertoast.showToast(
        msg: '删除失败，请重试',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIosWeb: 3,
        backgroundColor: Colors.white,
        textColor: Colors.black,
        fontSize: 16.0,
      );
    }
  }
}
